#include "launch.h"
#include "ui_launch.h"
#include <QPushButton>
#include <QSettings>
#include <QTextCodec>

Launch::Launch(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Launch)
{
    ui->setupUi(this);
    ui->buttonBox->button(QDialogButtonBox::Ok)->setText("选定");

    QSettings configFile(configFilePath, QSettings::IniFormat);
    configFile.setIniCodec(QTextCodec::codecForName("UTF-8"));

    configFile.beginGroup("Global");
    QString lastBoard=configFile.value("last_selected_board").toString();
    configFile.endGroup();

    QStringList sections = configFile.childGroups();
    foreach(QString item, sections)
    {
        if (item.contains("Board"))
        {
            configFile.beginGroup(item);
            QString boardName = configFile.value("NAME").toString();
            configFile.endGroup();

            ui->boardComboBox->addItem(boardName);
        }
    }

    if (!lastBoard.isEmpty())
    {
        ui->boardComboBox->setCurrentText(lastBoard);
    }
}

Launch::~Launch()
{
    delete ui;
}

QString Launch::getBoardName()
{
    return ui->boardComboBox->currentText();
}

QString Launch::findSectionByName(const QString &boardName)
{
    QSettings configFile(configFilePath, QSettings::IniFormat);
    configFile.setIniCodec(QTextCodec::codecForName("UTF-8"));
    QStringList sections = configFile.childGroups();
    foreach(QString item, sections)
    {
        configFile.beginGroup(item);
        if (configFile.value("NAME").toString() == boardName)
        {
            configFile.endGroup();
            return item;
        }
        configFile.endGroup();
    }

    return nullptr;
}

void Launch::on_boardComboBox_currentTextChanged(const QString &arg1)
{
    setWindowTitle("厨芯：" + arg1);
    QString curSection = findSectionByName(arg1);

    QSettings configFile(configFilePath, QSettings::IniFormat);
    configFile.setIniCodec(QTextCodec::codecForName("UTF-8"));
    configFile.beginGroup(curSection);

    /* 显示电路板图片，只有工厂模式才会显示，否则隐藏 */
    QString boardImage = configFile.value("IMG").toString();
    ui->imageLabel->setPixmap(QPixmap(boardImagePath + boardImage).scaled(ui->imageLabel->size()));

    configFile.endGroup();
}
